<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPermissionAnchorModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserExtContractModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\OpenShop\StartBusiness\OpenShopStartBusinessModel;
use App\Service\Guanyuan\CurlService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Feishu\ShopManualService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\Statistical\SignOrderStatisticalService;
use App\Support\OrganizationManageFsRobotSendSupport;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class OpenShopShangZeng extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'open_shop:shang_zeng_daily';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '商家增长-数据追踪 .';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private SignOrderStatisticalService $signOrderService;

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->signOrderService = new SignOrderStatisticalService();

        $part1 = $this->getPart1();
        $part2 = $this->getPart2();
        $part3 = $this->getPart3New();

//        dd($part3);


        $finalTmp = <<<STR
----------------------------------
# 商增每日分组业绩 
{$part1}
----------------------------------
# 本月签约完成率
{$part2}
----------------------------------
# 省区月度签约门店数 
{$part3}
STR;


        $companyDatum['manageId'] = self::getManageId(); // 总部日工


        OrganizationManageFsRobotSendSupport::send($companyDatum['manageId'],
            '商家增长 [数据追踪]', $finalTmp, 'feishuRobotDataDay');

    }

    private function getManageId()
    {
        if ('prod' == config('app.env')) {
            return 100;
        } else {
            return 99;
        }
    }

    private function getPart1()
    {
        $remitData = $this->signOrderService->getGYShangZengDaily();
        $groupList = $this->signOrderService->getZhaoShangGroup();

        $defaultTemplate = array_column($groupList, null, 'groupName');

        $remitData = array_column($remitData, null, 'gyGroup');

        foreach ($defaultTemplate as $key => $item) {
            if (!key_exists($key, $remitData)) {
                $remitData[$key] = [
                    'gyRemitDate'   => '',
                    'gyGroup'       => $key,
                    'gyCustomerNum' => 0,
                    'gyShopNum'     => 0,
                    'gyRemitMoney'  => 0,
                ];
            }
            $remitData[$key]['sort'] = $item['sort'];
        }


        // 手动添加排序
        foreach ($remitData as &$datum) {
            if (empty($datum['sort'])) {
                $datum['sort'] = 0;
            }
        }

        // 手动排序
        $remitData = arraySort($remitData, 'sort', SORT_DESC);

        // 输出 展示文字
        $str = '';
        foreach ($remitData as $one) {
            $str .= vsprintf('%s：%s个客户，%s个门店，%s万回款' . PHP_EOL,
                [$one['gyGroup'], $one['gyCustomerNum'], $one['gyShopNum'], $one['gyRemitMoney'] / 10000]);
        }

        $str = trim($str, PHP_EOL);

        return $str;
    }

    private function getPart2()
    {
        $remitData = $this->signOrderService->getGYQianYuePercent();

        $remitData = reset($remitData);

        $percent = bcmul($remitData['gySignPercentMonth'], 100, 2);
        // 输出 展示文字
        $str = <<<STR
本月签约客户数：{$remitData['gySignNumMonth']}个
本月签约门店数：{$remitData['gySignShopMonth']}个
本月签约完成率：{$percent}%
STR;

        $str = trim($str, PHP_EOL);

        return $str;
    }

    private function getPart3()
    {
        $dataSource = [
            'gyStatusWeekList' => $this->signOrderService->getGYStatusWeek(true),
        ];

        $allArea = $this->signOrderService->getInitAreaList([
            'newSignGWNumMonth'
        ]);

        foreach ($dataSource as $dsValue) {
            foreach ($dsValue as $dsvValue) {
                $code                            = $dsvValue['provinceCode'];
                $allArea[$code]['templateValue'] = array_merge($allArea[$code]['templateValue'],
                    $dsvValue['templateValue']);
            }
        }

        $resultFormatData = $this->signOrderService->formatCompanyDataSend($allArea);


        $companyData = [];
        // 整理数据
        foreach ($resultFormatData as $datum) {
            if (in_array($datum['name'], ['总部', '台湾分公司', '国外'])) {
                continue;
            }

            $companyData[] = [
                'name'              => $datum['name'],
                'newSignGWNumMonth' => $datum['templateValue']['newSignGWNumMonth']
            ];
        }

        $companyData = arraySort($companyData, 'newSignGWNumMonth');

        $str = '';
        foreach ($companyData as $one) {
            $str .= $one['name'] . $one['newSignGWNumMonth'] . '个' . PHP_EOL;
        }

        $str = trim($str, PHP_EOL);

        return $str;
    }

    private function getPart3New()
    {
        $companyList = $this->signOrderService->getGyCompanyList();

        $dataSource  = $this->signOrderService->getGyMonthSign();
        $companyData = array_column($dataSource, null, 'area');
        $str         = '';

        foreach ($companyList as $one) {
            if (empty($companyData[$one])) {
                $companyData[$one] = [
                    'area'           => $one,
                    'newSignShopNum' => 0
                ];
            }
        }

        $companyData = arraySort($companyData, 'newSignShopNum');

        foreach ($companyData as $one) {
            $str .= $one['area'] . $one['newSignShopNum'] . '个' . PHP_EOL;
        }

        $str = trim($str, PHP_EOL);

        return $str;
    }
}
